package com.herui.ota.service.iml;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.herui.ota.dao.desk.FileDeskStore;
import com.herui.ota.dao.mysql.FileSrcMapper;
import com.herui.ota.entity.FileSrc;
import com.herui.ota.enums.ResponseEnum;
import com.herui.ota.exception.ServiceException;
import com.herui.ota.service.FileSrcService;
import com.mlnx.common.utils.MyLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * author name: amanda.shan
 * create time: 2023-09-25 11:17:50
 */ 
@Service
public class FileSrcServiceIml extends BaseService<FileSrcMapper, FileSrc> implements FileSrcService {

	MyLog log = MyLog.getLog(getClass());

	@Autowired
	private FileDeskStore fileMongoStore;

	@Autowired
	@Override
	public void setBaseMapper(FileSrcMapper baseMapper) {
		super.setBaseMapper(baseMapper);
	}

	@Override
	public void download(String path, Integer skip, HttpServletRequest request, HttpServletResponse response) throws IOException {

		FileSrc fileSrc = getOne(new QueryWrapper<FileSrc>().eq("path", path));
		if (fileSrc == null){
			throw new ServiceException(ResponseEnum.DOWNLOAD_FAIL.getCode(), "文件不存在");
		}

		InputStream downloadStream = fileMongoStore.getDownloadStream(path);
		if (downloadStream == null){
			throw new ServiceException(ResponseEnum.DOWNLOAD_FAIL.getCode(), "打开文件失败");
		}

		int fileLength = fileSrc.getLength().intValue();
		String md5 = fileSrc.getMd5();
		String filename = fileSrc.getName();

		response.setContentType("application/octet-stream; charset=utf-8");
		response.setHeader("md5", md5);
		response.setContentLength(fileLength);
		if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
			response.setHeader("Content-Disposition", "attachment; filename="
					+ new String(filename.getBytes("UTF-8"), "ISO8859-1"));// firefox浏览器
		} else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			response.setHeader("Content-Disposition", "attachment; filename="
					+ URLEncoder.encode(filename, "UTF-8"));// IE浏览器
		} else {
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
		}

		OutputStream os = response.getOutputStream();

		if (skip != null){
			if (fileLength >= skip){
				downloadStream.close();
				os.flush();
				os.close();
			}else{
				downloadStream.skip(skip);
			}
		}

		byte[] bytesToWriteTo = new byte[1024];
		int len = 0;
		while ((len = downloadStream.read(bytesToWriteTo)) >0){
			os.write(bytesToWriteTo, 0, len);
		}

		downloadStream.close();
		os.flush();
		os.close();
	}

	@Override
	public String download(String path) throws IOException {


		FileSrc fileSrc = getOne(new QueryWrapper<FileSrc>().eq("path", path));
		if (fileSrc == null){
			throw new ServiceException(ResponseEnum.DOWNLOAD_FAIL.getCode(), "文件不存在");
		}

		InputStream downloadStream = fileMongoStore.getDownloadStream(path);
		if (downloadStream == null){
			throw new ServiceException(ResponseEnum.DOWNLOAD_FAIL.getCode(), "打开文件失败");
		}

		String encode = Base64.encode(downloadStream);
		downloadStream.close();
		return encode;
	}

	@Override
	public String upload(String filename, MultipartFile file) {

		try {
			OutputStream uploadStream = fileMongoStore.getUploadStream(filename);

			InputStream inputStream = file.getInputStream();
			int len = 0;
			byte[] bytes = new byte[1024];
			int sumLen = 0;
			while ((len  = inputStream.read(bytes))> 0){
				sumLen += len;
				uploadStream.write(bytes, 0, len);
			}
			uploadStream.close();

			FileSrc fileSrc = new FileSrc();
			fileSrc.setPath(filename);
			fileSrc.setLength((long) sumLen);
			save(fileSrc);

			return filename;

		} catch (IOException e) {
			log.error("保存文件失败", e);
			throw new ServiceException(ResponseEnum.DOWNLOAD_FAIL.getCode(), "打开文件失败");
		}
	}

	@Override
	public int start(String filename) {
		return 0;
	}

	@Override
	public void end(Integer taskId) {

	}

	public static void main(String[] args) {
//		System.out.println(Base64.encode("desk\\test\\1.png"));

		byte[] bytes = new byte[2*1024*1024];
		for (int i = 0; i < 2*1024*1024; i++) {
			bytes[i] = (byte) i;
		}
		String encode = Base64.encode(bytes);
		System.out.println(encode);

		byte[] decode = Base64.decode(encode);
		System.out.println();
	}
}

